package com.wsx.ones.boot.core.redis;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedisPool;

public class RedisShardedUtil {
	
	public static Map<String, ShardedJedisPool> shardedJedisPoolMap = new ConcurrentHashMap<String, ShardedJedisPool>();
	

	public static ShardedJedisPool getShardedJedis(String group) {
		ShardedJedisPool shardedJedisPool = null;
		if (shardedJedisPoolMap.containsKey(group)) {
			return shardedJedisPoolMap.get(group);
		}
		
		if (null == RedisConfig.redisGroup) {
			RedisConfig.redisGroup = RedisConfig.getRedisGroup();
		}
		
		List<RedisBean> redisList = RedisConfig.redisGroup.get(group);
		if (null == redisList || redisList.size() <= 0) {
			return null;
		}
		
		JedisPoolConfig poolConfig = getJedisPoolConfig();
		List<JedisShardInfo> redisShardList = getReidsList(redisList);
		shardedJedisPool = new ShardedJedisPool(poolConfig, redisShardList);
		shardedJedisPoolMap.put(group, shardedJedisPool);
		return shardedJedisPool;
	}


	/**
	 * 
	 * @param redisList
	 * @return
	 */
	private static List<JedisShardInfo> getReidsList(List<RedisBean> redisList) {
		int size = redisList.size();
		List<JedisShardInfo> jedisShardInfos = new ArrayList<JedisShardInfo>(size);
		JedisShardInfo shardInfo = null;
		for (int i = 0; i < size; i++) {
			RedisBean redisBean = redisList.get(i);
			shardInfo = new JedisShardInfo(redisBean.getHostIp(), Integer.valueOf(redisBean.getPort()), 
					Integer.valueOf(redisBean.getTimeout()), redisBean.getName());
			
			jedisShardInfos.add(shardInfo);
		}
		return jedisShardInfos;
	}


	/**
	 * 
	 * @return
	 */
	private static JedisPoolConfig getJedisPoolConfig() {
		JedisPoolConfig poolConfig = new JedisPoolConfig();
		poolConfig.setMaxTotal(500);
		poolConfig.setMaxIdle(1000 * 60);
		poolConfig.setMaxWaitMillis(1000 * 10);
		poolConfig.setTestOnBorrow(true);
		return poolConfig;
	}
}
